package controllers

import (
	"ecomserver/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"strconv"
	"strings"
	"time"
)

type OrderController struct {
	beego.Controller
}

func (this *OrderController)ShowOrder(){

	skuids := this.GetStrings("skuid")

	if len(skuids) == 0{
		beego.Info("请求数据错误")
		this.Redirect("/user/cart", 302)
		return
	}
	goodsBuffer := make([]map[string]interface{}, len(skuids))
	conn, err := redis.Dial(models.GetRedisAddr())
	if err != nil{
		beego.Info(err)
		return
	}
	defer conn.Close()
	o := orm.NewOrm()
	var user models.User
	user.Name =	GetUser(&this.Controller)
	err = o.Read(&user, "Name")
	if err != nil{
		beego.Info(err)
		return
	}
	totalCount, totalPrice := 0, 0
	for index, skuid := range skuids{
		temp := make(map[string]interface{})
		id, _ := strconv.Atoi(skuid)

		var goodsSku models.GoodsSKU
		goodsSku.Id = id
		err := o.Read(&goodsSku)
		if err != nil{
			continue
		}
		temp["goods"] = goodsSku
		count, _ := redis.Int(conn.Do("hget", "cart_"+strconv.Itoa(user.Id), id))
		temp["count"] = count
		temp["amount"] = count * goodsSku.Price

		totalCount += count
		totalPrice += count * goodsSku.Price
		goodsBuffer[index] = temp
	}
	this.Data["goodsBuffer"] = goodsBuffer

	//get user all addr
	var addrs []models.Address
	o.QueryTable("Address").RelatedSel("User").Filter("User", user).All(&addrs)
	this.Data["addrs"] = addrs
	this.Data["totalCount"] = totalCount
	this.Data["totalPrice"] = totalPrice
	transPrice := 10
	this.Data["transPrice"] = transPrice

	this.Data["realPrice"] = totalPrice + transPrice
	this.Data["skuids"] = skuids


	this.TplName = "place_order.html"
}
func (this *OrderController)AddOrder(){

	addrid,_ := this.GetInt("addrid")
	payid,_ := this.GetInt("payid")
	skuids := this.GetString("skuids")

	//totalPrice,_ := this.GetInt("totalPrice")
	totalCount,_ := this.GetInt("totalCount")
	transferPrice,_ := this.GetInt("transferPrice")
	realyPrice,_ := this.GetInt("realyPrice")

	resp := make(map[string]interface{})
	defer this.ServeJSON()
	if len(skuids) == 0{
		beego.Info("获取数据错误")
		resp["code"] = 1
		this.Data["json"] = resp
		return
	}
	o := orm.NewOrm()

	//事务
	o.Begin()

	var user models.User

	user.Name = GetUser(&this.Controller)
	err := o.Read(&user, "Name")
	if err != nil{
		beego.Info(err)
		resp["code"] = 2
		resp["msg"] = "出现错误"
		this.Data["json"] = resp

		return
	}
	var addr models.Address
	addr.Id = addrid
	err = o.Read(&addr)

	if err != nil{
		beego.Info(err)
		resp["code"] = 3
		resp["msg"] = "出现错误"
		this.Data["json"] = resp
		return
	}

	var order models.OrderInfo
	order.OrderId = time.Now().Format("2006010215030405") + strconv.Itoa(user.Id)
	order.User = &user
	order.Orderstatus = 1
	order.PayMethod = payid
	order.TotalCount = totalCount
	order.TotalPrice = realyPrice
	order.TransitPrice = transferPrice
	order.Address = &addr

	_,err = o.Insert(&order)
	if err != nil {
		beego.Info(err)
		resp["code"] = 4
		resp["msg"] = "出现错误"
		this.Data["json"] = resp
		return
	}
	conn, err := redis.Dial(models.GetRedisAddr())
	if err != nil {
		beego.Info(err)
		resp["code"] = 8
		resp["msg"] = "出现错误"
		this.Data["json"] = resp
		return
	}

	//订单商品表插入数据
	skuids = strings.TrimLeft(skuids, "[")
	skuids = strings.TrimRight(skuids, "]")

	for _, skuid := range strings.Split(skuids, " "){

			id, _ := strconv.Atoi(skuid)
			var goods models.GoodsSKU
			goods.Id = id
			i := 3
			for i > 0{

				err := o.Read(&goods)

				if err != nil{
					resp["code"] = 7
					resp["msg"] = "商品不存在"
					this.Data["json"] = resp
					o.Rollback()
					return
				}

				var orderGoods models.OrderGoods

				orderGoods.GoodsSKU = &goods
				orderGoods.OrderInfo = &order

				count, _  := redis.Int(conn.Do("hget", "cart_"+strconv.Itoa(user.Id), id))

				if count > goods.Stock{

					resp["code"] = 6
					resp["msg"] = "商品库存不足"
					this.Data["json"] = resp
					o.Rollback()
					beego.Info("rollback")
					return
				}
				preStock := goods.Stock
				orderGoods.Count = count
				orderGoods.Price = count * goods.Price
				o.Insert(&orderGoods)
				goods.Stock -= count
				goods.Sales += count

				updateCount, _ :=o.QueryTable("GoodsSKU").Filter("Id", goods.Id).Filter("Stock", preStock).
					Update(orm.Params{"Stock":goods.Stock, "Sales":goods.Sales})
				if updateCount == 0{
					if i > 0{
						i -= 1
						continue
					}
					resp["code"] = 7
					resp["msg"] = "商品库存改变,订单提交失败"
					this.Data["json"] = resp
					o.Rollback()
					return
				}else{
					_, err := conn.Do("del", "cart_" + strconv.Itoa(user.Id))
					beego.Info(err)
					break
				}
			}
	}
	o.Commit()
	//return
	resp["code"] = 5
	resp["msg"] = "ok"
	this.Data["json"] = resp
}